package com.tiance.web.controller.front;

import com.alibaba.fastjson.JSON;
import com.tiance.constants.CommonConstants;
import com.tiance.dal.dataobject.IntegrationChangeRecordDO;
import com.tiance.dal.dataobject.MemberDO;
import com.tiance.domainservice.domain.MemberAuthenticationInfoDomain;
import com.tiance.domainservice.domain.MemberDomain;
import com.tiance.domainservice.service.MemberAuthService;
import com.tiance.domainservice.service.MemberService;
import com.tiance.domainservice.service.SignInService;
import com.tiance.enums.*;
import com.tiance.exception.BusinessException;
import com.tiance.integration.cache.MapCacheUtil;
import com.tiance.integration.config.CommonProperties;
import com.tiance.integration.wechat.WechatClient;
import com.tiance.integration.wechat.WechatPayUtil;
import com.tiance.integration.wechat.WxUserInfo;
import com.tiance.utils.BeanConverterUtil;
import com.tiance.vo.MemberAuthenticationInfoVO;
import com.tiance.vo.UploadVO;
import com.tiance.web.aspect.OperatorControllerLog;
import com.tiance.domainservice.checker.MemberParamsChecker;
import com.tiance.web.controller.base.FrontController;
import com.tiance.web.controller.common.BaseResponse;
import com.tiance.web.convertor.ModelConvert;
import com.tiance.vo.MemberVO;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Date;

/**
 *
 * @author 雷霆
 * @version 1.0.0
 * @date$ 2019/1/30
 *
 * Description：会员管理
 *
 * Modification History:
 *
 */
@Controller
@RequestMapping(value = "/front/memberCenter")
public class MemberController extends FrontController {
    private static String LOG_PREFIX ="MemberController| 会员控制器===>";



    @Autowired
    private CommonProperties commonProperties;





    @Autowired
    private MemberService     memberService;
    @Autowired
    private MemberAuthService memberAuthService;
    @Autowired
    private SignInService     signInService;
    @RequestMapping(value = "/toIndex.action")
    @OperatorControllerLog(operationLogType= OperateTypeEnum.FRONT_INTERFACE,operationName="跳转到会员注册页面")
    public String toIndex(HttpServletRequest request, Model model,MemberVO memberVO)  {
        try {
            HttpSession session=request.getSession();

            Object openid=session.getAttribute(CommonConstants.OPENID);
            if(null==openid){
                logger.info("开始获取会员OpenId");
                openid = WechatPayUtil.getWeChatOpenId(request, commonProperties.getWechatAppId(),commonProperties.getWechatSecret());
                logger.info("weixin返回的openId：" + openid);
                session.setAttribute(CommonConstants.OPENID,openid);
            }

            memberVO.setOpenid((String)openid);

            MemberDomain memberDomain = ModelConvert.memberVO2MemberDomain(memberVO);
            MemberDO memberDO = memberService.queryMember(memberDomain);

            if(null==memberDO){
                WxUserInfo wxUserInfo= WechatClient.getUserInfo(memberVO.getOpenid());

            if(null==wxUserInfo||null==wxUserInfo.getOpenid()){
                throw new BusinessException("未获取到微信用户信息!");
            }

            ModelConvert.wxUserInfo2MemberDomain(memberDomain,wxUserInfo);

            if(MapCacheUtil.lock(memberVO.getOpenid())){
                try {
                    memberService.addGuest(memberDomain);
                }finally {
                    MapCacheUtil.unlock(memberVO.getOpenid());
                }
            }else{
                throw new BusinessException("该请求正在处理中，请稍后再试!");
            }
            }

            memberDO = memberService.queryMember(memberDomain);
            BeanConverterUtil.copyProperties(memberVO, memberDO);
            memberVO.setMemberId(memberDO.getId());
            String signStatus=signInService.queryMemberSignStatus(memberVO.getId());
            memberVO.setSignInStatus(signStatus);
            session.setAttribute(CommonConstants.MEMBER_ID,memberDO.getId());

            model.addAttribute("memberVO", memberVO);
        }catch(BusinessException e1){
        logger.info(LOG_PREFIX+"会员查询失败，失败原因：",e1);
        model.addAttribute("errorInfo","会员查询失败，请稍后重试!");
        return  "/front/error";
         }catch (Exception e2){
        model.addAttribute("errorInfo","会员查询失败,请稍后重试!");
        logger.error(LOG_PREFIX+"会员查询失败,失败原因",e2);
        return "/front/error";
         }

        return "/front/index";

    }

    @RequestMapping(value = "/toMemberRegistertest.action",method = RequestMethod.GET)
    @OperatorControllerLog(operationLogType= OperateTypeEnum.FRONT_INTERFACE,operationName="跳转到会员注册页面")
    public String toMemberRegistertest() {
        return "/front/test/memberRegister";
    }
    @RequestMapping(value = "/toUploadIDCard.action",method = RequestMethod.GET)
    @OperatorControllerLog(operationLogType= OperateTypeEnum.FRONT_INTERFACE,operationName="跳转到上传身份证页面")
    public String toUploadIDCard() {
        return "/front/Idcard";
    }



    @RequestMapping(value = "/toMemberRegister.action",method = RequestMethod.GET)
    @OperatorControllerLog(operationLogType= OperateTypeEnum.FRONT_INTERFACE,operationName="跳转到会员注册页面")
    public String toMemberRegister(HttpServletRequest request,Model model, MemberVO memberVO) {
        HttpSession session=request.getSession();
        try{
        Object openid=session.getAttribute(CommonConstants.OPENID);
        if(null!=openid){
            memberVO.setOpenid((String)openid);
        }
         WxUserInfo wxUserInfo= WechatClient.getUserInfo(memberVO.getOpenid());
        if(null==wxUserInfo||null==wxUserInfo.getOpenid()){
            throw new BusinessException("未获取到微信用户信息!");
        }
        memberVO=ModelConvert.wxUserInfo2MemberVo(memberVO,wxUserInfo);

    }catch(BusinessException e1){
        logger.info(LOG_PREFIX+"会员查询失败，失败原因：",e1);
        model.addAttribute("errorInfo","会员查询失败，请稍后重试!");
        return  "/views/initFail";
    }catch (Exception e2){
        model.addAttribute("errorInfo","会员查询失败,请稍后重试!");
        logger.error(LOG_PREFIX+"会员查询失败,失败原因",e2);
        return "/views/initFail";
    }

        model.addAttribute("memberVO",memberVO);
        return "/front/myinformation";

    }

    @RequestMapping(value = "/queryMember.action",method = RequestMethod.POST)
    @ResponseBody
    @OperatorControllerLog(operationLogType=OperateTypeEnum.FRONT_INTERFACE,operationName="查询会员")
    public BaseResponse queryMember(Model model,MemberVO memberVO){
        BaseResponse<MemberVO> backResponse=new BaseResponse();

        logger.info("开始查询会员，请求参数:{}", JSON.toJSONString(memberVO));

        try {
            MemberParamsChecker.checkQueryMember(memberVO);
            MemberDomain memberDomain= ModelConvert.memberVO2MemberDomain(memberVO);
            MemberDO memberDO= memberService.queryMember(memberDomain);
            if(null!=memberDO){
                BeanConverterUtil.copyProperties(memberVO, memberDO);
            }
            backResponse.setResult(memberVO);
            backResponse.setResponseCode(ErrorCodeEnum.SUCCESS.getCode());
            backResponse.setSuccess(true);

        }catch(BusinessException e1){
            logger.info(LOG_PREFIX+"会员查询失败，失败原因：",e1);
            backResponse.setSuccess(false);
            backResponse.setMessage(e1.getMessage());
        }catch (Exception e2){
            logger.error(LOG_PREFIX+"会员查询失败,失败原因",e2);
            backResponse.setSuccess(false);
            backResponse.setMessage("会员查询失败");
        }
        logger.info("结束查询会员，返回数据:{}", model);
        return  backResponse;

    }

    @RequestMapping(value = "/updateMember.action",method = RequestMethod.POST)
    @ResponseBody
    @OperatorControllerLog(operationLogType=OperateTypeEnum.FRONT_INTERFACE,operationName="更新会员")
    public String updateMember(HttpServletRequest request, Model model,MemberVO memberVO){
        logger.info("开始更新会员，请求参数:{}", JSON.toJSONString(memberVO));

        try {
            MemberParamsChecker.checkUpdateMember(memberVO);
            MemberDomain memberDomain= ModelConvert.memberVO2MemberDomain(memberVO);
            if(MapCacheUtil.lock(memberVO.getId()+"")) {
                MemberDO memberDO = memberService.updateMember(memberDomain);
                BeanConverterUtil.copyProperties(memberVO, memberDO);
                model.addAttribute("memberVO", memberVO);
            }else {
                throw new BusinessException("该会员正在被操作中，请稍后再试!");
            }

        }catch(BusinessException e1){
            logger.info(LOG_PREFIX+"会员更新失败，失败原因：",e1);
            model.addAttribute("errorInfo","会员更新失败，请稍后重试!");
            return  "/front/error";
        }catch (Exception e2){
            model.addAttribute("errorInfo","会员更新失败,请稍后重试!");
            logger.error(LOG_PREFIX+"会员更新失败,失败原因",e2);
            return "/front/error";
        }
        logger.info("结束更新会员，返回数据:{}", model);
        return  "/front/error";

    }

    @RequestMapping(value = "/memberRegister.action",method = RequestMethod.POST)
    @OperatorControllerLog(operationLogType=OperateTypeEnum.FRONT_INTERFACE,operationName="注册会员")
    public String register(HttpServletRequest request, Model model,MemberVO memberVO){

        logger.info("开始注册会员，请求参数:{}", JSON.toJSONString(memberVO));

        try {
            HttpSession session=request.getSession();
            Object memberId=session.getAttribute(CommonConstants.MEMBER_ID);
            if(null!=memberId){
                memberVO.setId((Long)memberId);
            }
            MemberParamsChecker.checkRegisterMember(memberVO);
            MemberDomain memberDomain= ModelConvert.memberVO2MemberDomain(memberVO);

            if(!MapCacheUtil.lock(memberVO.getId()+"")){
                throw new BusinessException("该请求正在处理中，请稍后再试!");
            }
            memberService.register(memberDomain);

        }catch(BusinessException e1){
            logger.info(LOG_PREFIX+"会员注册失败，失败原因：",e1);
            memberVO.setErrorInfo(e1.getMessage());
            model.addAttribute("memberVO",memberVO);
            return  "/front/myinformation";
        }catch (Exception e2){
            logger.error(LOG_PREFIX+"会员注册失败,失败原因",e2);
            memberVO.setErrorInfo("会员注册失败,请稍后重试!");
            model.addAttribute("memberVO",memberVO);
            return  "/front/myinformation";

        }finally {
            MapCacheUtil.unlock(memberVO.getId()+"");
        }

        logger.info("注册会员成功");
        return  "redirect:/front/memberCenter/toIndex.action";

    }



}